const express = require('express');
const multer  = require('multer');
const router = express.Router();
const db = require("../../dbConfig.js");
const serviceImage=require('../../service/image');

// 探索，获取所有用户的图片(不是私密的图片)  (分页)
router.get('/getExplore',async (req,res,next)=>{ 
  let {page}=req.query;
  let result=await serviceImage.getExplore(page);
  res.json({result:result,success:true}); 
})

// 探索，获取所有图片总数(不是私密的图片)
.get('/getExploreCount',async(req,res)=>{ 
  let result=await serviceImage.getExploreCount();
  res.json({imgCount:result[0].count,success:true});
})
 
.get('/getTestImg',async(req,res)=>{ 
	let sql=`select imgUrl url from aaa where id=1`;
  let result=await db(sql);
  let [{url}]=result;
  if(!url) return res.json([]);
  let imgList=url.split(',');
  let arr=[];
  imgList.map((val,index)=>{
    arr.push({
     id:index,
     url:val
   })
  })
  res.json(arr);
})

.get('/deleteTestImg',async(req,res)=>{ 
	let {list}=req.query;
	let sql=`update aaa set imgUrl=? where id=1`;
  let result=await db(sql,list);
  res.json({success:true});
})

function timestampToTime(timestamp) {
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  let H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() ;
  let MI = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() ;
  let S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() ;
  return Y + M + D+'_'+ H + "." + MI + "." + S;
}

// 示例
let imageList=[];
let Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, "./images");
  },
  filename: function (req, file, callback) {
    let d=timestampToTime(new Date().getTime());
    let fname=d+'—'+file.originalname;
    fileName='http://localhost:2008/images/'+fname;
    imageList.push(fileName); 
    callback(null,fname); 
  }
});
let upload = multer({ storage: Storage }).array("file",3); 
router.post("/uploadTest",upload, function (req, res) {
  res.json({
    imgpath:imageList
  });
  imageList=[];
  // upload(req, res,async function (err) {
  //   if (err) {
  //     console.log(err);
  //     return  res.send("Something went wrong!");
  //   }  
  //   // let sqlSelect='select imgUrl url from aaa where id=1';
  //   // let [{url}]=await db(sqlSelect);
  //   // let sql=`update aaa set imgUrl=concat(imgUrl,',',?) where id=1`;
  //   // if(!url){
  //   //   console.log('imgUrl是空的。。。。。。。。。。。');
  //   //   sql=`update aaa set imgUrl=concat(imgUrl,?) where id=1`;
  //   // }
  //   // await db(sql,[imageList]);
  //   // console.log('concat success...............');
  //   res.json({
  //     imgpath:imageList
  //   });
  //   imageList=[];
  // });
})
module.exports=router;

